package com.zwb.demo.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Map;

public class MyFreeMarkerUtils {

    public static void createFile(String templateName, String filePath, String fileName, Object dataMap) throws IOException, TemplateException {
        //创建配置实例
        Configuration configuration = new Configuration();
        //设置编码
        configuration.setDefaultEncoding("utf-8");
        //ftl模板文件
        configuration.setClassForTemplateLoading(MyFreeMarkerUtils.class, "/templates/");
        //获取模板
        Template template = configuration.getTemplate(templateName);
        //输出文件
        File outFile = new File(filePath + File.separator + fileName);

        //如果输出目标文件夹不存在，则创建
        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }

        //将模板和数据模型合并生成文件
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));


        //生成文件
        template.process(dataMap, out);

        //关闭流
        out.flush();
        out.close();

    }
}
